package com.mkbk.service.impl;


import com.mkbk.mapper.UserMapper;
import com.mkbk.model.User;
import com.mkbk.service.UserService;
import com.mkbk.utils.MD5Utils;
import com.mkbk.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.UUID;

public class UserServiceImpl implements UserService {

    UserMapper userMapper;

    /**
     * 用户注册
     */
    @Override
    public void register(User user) {
        // 获取加密盐
        // 生成 32 位加密的秘钥
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        user.setSalt(salt);
        // 对用户的密码进行加密
        user.setPassword(MD5Utils.stringToMD5(user.getPassword() + salt));
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.register(user);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    /**
     * 登录
     */
    @Override
    public User login(User user) {
        SqlSession sqlSession = MybatisUtil.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
        User userResult = userMapper.login(user);
        if (userResult != null) {
            if (userResult.getPassword().equals(user.getPassword())) {
                System.out.println("登录成功");
            } else {
                System.out.println("密码错误");
            }
        } else {
            System.out.println("用户名不存在");
        }
        return userResult;
    }


}
